# 导入蓝图模块
from flask import Blueprint,request,jsonify,json
import json
from db import db1
# 实例化
bp_course = Blueprint("course",__name__)
from comm import get_data

#接口
@bp_course.route('/couponM',methods=['POST','GET','PUT','DELETE'])
def couponM():
    # 添加
    if request.method == "POST":
        #获取用户输入
        data = get_data()
        #构造sql语句
        sql = "insert into coupon values(0,'%s',%d,'%s','%s')" % (data['name'],int(data['total']),data['stime'],data['etime'])
        # pymysql
        db1.insert(sql)
        #返回结果
        return jsonify({'code':200})
    
    # 查看
    elif request.method == 'GET':
        # 根据id获取数据
        id = request.args.get('id')
        sql = "select * from coupon where id=%d" % (int(id))
        res =db1.find(sql)
        return jsonify({'code':200,'coupon':res})

    # 修改
    elif request.method == "PUT":
        # 修改
        # 获取用户输入
        id = request.args.get('id')
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造sql语句 update 表名 set 字段名1=值,字段名2=值 where id=1
        sql = "update coupon set name='%s',total=%d,starttime='%s',endtime='%s' where id=%d"%(data['name'],int(data['total']),data['stime'],data['etime'],int(id))  #小猴同志所输
        db1.insert(sql)
        return jsonify({'code':200})

    # 删除
    elif request.method == "DELETE":
        # 获取id
        id = request.args.get('id')
        sql = "delete from coupon where id=%d"%(int(id))
        db1.insert(sql)
        return jsonify({'code':200})

#部门管理
@bp_course.route('/deptM',methods=['POST','GET'])
def deptM():
    if request.method == "POST":
        data = get_data()
        #判断名字是否已经存在
        sql = "select id from dept where name='%s'"%(data['name'])
        res = db1.find(sql)
        #存在直接返回
        if res:
            return jsonify({"code":10011,'mes':'已经存在'})
        #不存在添加
        else:
            sql = "insert into dept(name) values('%s')"%(data['name'])
            db1.insert(sql)
            return jsonify({"code":200})
    else:
        sql = "select * from dept"
        res = db1.findall(sql)
        return jsonify({"code":200,'list':res})      

# 员工添加接口
@bp_course.route('/empM',methods=['POST','GET'])
def empM():
    if request.method == "POST":
        data = get_data()
        #添加员工
        sql = "insert into emp values(0,'%s',%d,%.2f,%d)"%(data['name'],int(data['sex']),float(data['salary']),int(data['dept_id']))
        db1.insert(sql)
        #更新部门表员工总数
        sql1 = 'select total from dept where id=%d'%(int(data['dept_id']))
        res = db1.find(sql1)
        total = int(res['total'])+1
        sql2 = 'update dept set total=%d where id=%d'%(total,int(data['dept_id']))
        db1.insert(sql2)
        return jsonify({"code":200})

import os
from myfiles import myfile

# 文件上传
@bp_course.route('/upload',methods=['POST'])
def upload():
    file = request.files['file']
    cityid = request.form['cityid']
    # 创建文件夹
    myfile.file_mkdir(cityid)
    # 图片上传
    file.save(os.path.join('../static/upload/'+str(cityid),file.filename))
    return jsonify({'code':200,'url':'/static/upload/'+str(cityid)+'/'+file.filename})

# 景点操作接口
@bp_course.route('/scenicM',methods=['POST','GET'])
def scenicM():
    if request.method == 'POST':
        # 图片上传,vue封装formdata
        data = request.form
        # 添加景点
        sql = "insert into scenic(title,price,typeid) values('%s',%.2f,%d)"%(data['title'],float(data['price']),int(data['typeid']))
        db1.insert(sql)
        # 获取新的id
        sql1 = "select id from scenic where title='%s'" % (data['title'])
        res = db1.find(sql1)
        # 文件上传,上传成功图片路径
        file = request.file['file']

        myfile.file_mkdir(str(res['id']))
        file.save(os.path.join('../static/upload/'+str(res['id']),file.filename))
        # 组装数据添加
        sql3 = "upload scenic srt pic='%s' where id = %d" % ('/static/upload/'+str(res['id'])+"/"+file.filename,int(res['id']))
        db1.insert(sql3)
    else:
        sql = "select * from scenic"
        res = db1.findall(sql)
        return jsonify({"code":200,'list':res})

# 查询所有景区
@bp_course.route('/citym')
def citym():
    sql = "select id,name from city"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})

@bp_course.route('/prom',methods=['POST',"GET"])
def prom():
    if request.method == "POST":
        data = get_data()
        sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')" % (data['title'],float(data['price']),int(data['city_id']),data['pic'])
        db1.insert(sql)
        return jsonify({"code":200})
    else:
        #当前页
        page = request.args.get('page')
        #每页面显示多少条
        page_size=2
        #计算开始下标
        start = (int(page)-1)*page_size
        #根据分类id查询分类下商品
        cityid = request.args.get('cityid')
        #定义总条数为0
        total = 0
        if  cityid == '0':
            sql = "select * from product order by price %s limit %d,%d"%(sort,start,page_size)
            #查询总条数
            sql1 =  "select count(id) from product"
            res = db1.find(sql1)
            total = res['count(id)']
        else:
            sql = "select * from product where city_id=%d limit %d,%d"%(int(cityid),start,page_size)
            #查询总条数
            sql1 =  "select count(id) from product where city_id=%d"%(int(cityid))
            res = db1.find(sql1)
            total = res['count(id)']

        res = db1.findall(sql)
        return jsonify({"code":200,'list':res,'total':total})

# 获取分类接口
@bp_course.route('/cateM')
def cateM():
    sql = "select * from yptype"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})

import datetime
# 获取记录接口
@bp_course.route('/recordM')
def recordM():
    # 获取分类id
    id = request.args.get('id')
    if id == '0':
        sql = "select * from record"
    else:
        sql = "select * from record where typeid=%d" % (int(id))
    res = db1.findall(sql) 
    list = []
    for i in res:
        dict={'id':i['id'],'stime':datetime.datetime.strftime(i['stime'],'%Y-%m-%d'),'etime':datetime.datetime.strftime(i['etime'],'%Y-%m-%d'),'money':float(i['money'])}
        list.append(dict)
    return jsonify({"code":200,'list':list})

@bp_course.route('/datailM')
def datailM():
    id =request.args.get('id')
    sql = "select * from record where id =%d"%(int(id))
    res =db1.find(sql)
    record ={'id':res['id'],'stime':datetime.datetime.strftime(res['stime'],'%y-%m-%d'),'money':float(res['money'])}
    return jsonify({"code":200,'record':record})
 
#获取分类接口
@bp_course.route('/orderM',methods=['GET','PUT'])
def orderM():
    if request.method == "PUT":
        id = request.args.get('id')
        sql = "select * from orders where id=%d"%(int(id))
        res = db1.find(sql)
        #判断状态原来为1改成2，原来为2改成1
        status = 2
        if int(res['status']) == 2:
            status=1            
        
        #执行更新操作
        sql1 = "update orders set status=%d where id=%d"%(status,int(id))
        db1.insert(sql1)
        return jsonify({"code":200})

    else:
        #当前页
        page = int(request.args.get('page'))
        #每页显示多少条
        page_size = int(request.args.get('page_size'))
        start = (page-1)*page_size
        sql = "select * from orders limit %d,%d"%(start,page_size)
        res = db1.findall(sql)
        #总条数
        sql1 = "select count(id) from orders"
        res1 = db1.find(sql1)
        return jsonify({"code":200,'list':res,'total':res1['count(id)']})

@bp_course.route('/orderDetaiM')
def orderDetaiM():
    
    pass

# 红包测试接口
@bp_course.route('/sendmoney',)
def sendmoney():
    money = request.args.get('money')
    # 对数据将进行有效性验证
    if not money:
        return jsonify({"code":"10011",'mes':'请输入金额'})
    else:
        try:
            # 格式验证
            money = float(money)
        except:
            return jsonify({"code":10012,'mes':'格式有误'})
    if money < 200 and money > 0.01:
        return jsonify({'code':200})
    else:
        return jsonify({'code':10013})

# 添加测试用例接口
@bp_course.route('/senMony',methods=['POST'])
def senMony():
    data = get_data
    sql = "insert into test_record('name','url','method','params','result') values('%s','%s','%s',%s,'%s')" % (date['name'],date['url'],date['method'],date['params'],date['result'])
    return jsonify({"code":200})

# 读取表测试及生成报告
@bp_course.route('/test_sendMoney')
def test_sendMoney():
    #读取数据库
    sql = "select * from test_record where status=1"
    res = db1.findall(sql)
    list=[]
    for i in res:
        flag = "失败"
        params = json.loads(i['params'])
        if i['method'] == "get":
            mes = requests.get(i['url'],params=params)
        elif i['method'] == "post":
            mes = requests.post(i['url'],data=params)
        mm = json.loads(mes.text)
        if mm['code'] == int(i['result']):
            flag='成功'
        str={"name":i['name'],"请求地址":i['url'],"返回信息":mes.text,"测试结果":flag}
        list.append(str)
        filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d')
        with open(os.path.join('./logs/'+filename+'.txt'),'w') as f:
            f.write(json.dumps(list,ensure_ascii=False))


# 发送验证码
import re,time,random
@bp_course.route('/sendSms',methods=['POST'])
def sendSms():
    #获取手机号
    data = get_data()
    try:
         mobile = data['mobile']  
    except:
       return jsonify({"code":10011,'mes':'不能为空'})

    #验证手机号是否合法
    res = re.match('^1[3-9]\d{9}$',mobile)
    if not res:
        return jsonify({"code":10010,'mes':'手机号不合法'})
    #检查上次发送是否超过一分钟，1分钟内不能发
    sql = "select stime from trecord where mobile='%s' order by id desc limit 1"%(str(mobile))
    record = db1.find(sql)
    if record:
        #判断时间是否在一分钟以内
        seconds = int(time.time())-int(record['stime'])
        if seconds<60:
            return jsonify({"code":10012,"mes":'一分钟内不能重复发送'})
    #生成验证码，发送
    code = random.randint(100000,999999)
    #当发送成功写入记录表
    sql2 = "insert into trecord(mobile,code,stime) values('%s',%d,%d)"%(str(mobile),code,int(time.time()))
    db1.insert(sql2)
    return jsonify({"code":200,'mes':'发送成功'})
    
# 验证码登录接口
@bp_course.route('/tlogin',methods=['POST'])
def tlogin():
    #获取手机号验证码
    data = get_data()
    #通过手机号去记录中表查询，查最近的一条
    sql = "select code,stime from trecord where mobile='%s' order by id desc limit 0,1" % (data['mobile'])
    res = db1.find(sql)
    #验证码过期时间验证
    if int(time.time())-int(res['stime'])>60:
        return jsonify({"code":10020,'mes':'验证码已经过期，重新发送'})
    #验证是否相同2
   
    if res['code'] == int(data['code']):
        #用户表中查询手机号是否存在
        sql1 = "select id from tuser where mobile='%s'"%(data['mobile'])
        user = db1.find(sql1)
        #存在返回登录成功userid
        if user:
            return jsonify({"code":200,'userid':user['id'],'mes':'登录成功'})
        #不存在添加新用户返回userid
        sql2 = "insert into tuser(mobile) values('%s')"%(data['mobile'])
        db1.insert(sql2)
        sql3 = "select id from tuser where mobile='%s'"%(data['mobile'])
        user3 = db1.find(sql3)
        return jsonify({"code":200,'userid':user3['id']})
    else:
        return jsonify({"code":10021,'mes':'验证码输入错误'})

# 搜索接口
@bp_course.route('/search')
def search():
    # 获取数据
    title = request.args.get('title')
    # 判断是否为空格 去掉空格
    title = title.strip()
    if not title:
        return jsonify({{"code":200,"mes":"搜索内容不能为空"}})
    # 判断长度 1-10
    if 1<=len(title)<=10:
        # 数据查询
        sql="select * from goods where title like '%"+title+"%'"
        print(sql)
        res =db1.findall(sql)
        # 写入记录表
        ip = request.remote_addr
        sql2 = "insert into grecord(title,ip) values('%s','%s')"%(title,ip)
        # 返回结果
        db1.insert(sql2)
        return jsonify({"code":200,'list':res})
    else:
        return jsonify({"code":10031,'mes':'长度不合法'})

# 商品添加接口
@bp_course.route('/evaluate',methods=['POST','GET'])
def evaluate():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into bl(good_id,title) values(%d,'%s')" % (int(data['good_id']),(data['title']))
        db1.insert(sql)
        return jsonify({'code':200})

    else:
        id = request.args.get('id')
        if id:
            sql = "select * from bl where id=(%d)" % (int(id))
            res = db1.find(sql)
            return jsonify({"code":200,'mes':res})
        else:
            sql = "select name from sp"
            res = db1.findall(sql)
            return jsonify({'code':200,'mes':res})


# 登录接口
@bp_course.route('/blogin',methods=['POST'])
def blogin():
    # 获取用户输入
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    # 判断用户名密码是否为空
    try:
        username = data['username']
        password = data['password']
    except:
        return jsonify({'code':10010,'mes':'用户名和密码不能为空'})

    if not all([username,password]):
        return jsonify({'code':10010,'mes':'用户名和密码不能为空'})
    # 根据用户名去数据库查
    sql = "select * from author where username='%s'" % (username)
    mes = db1.find(sql)
    if mes:
        # 查看到比对密码
        if mes['password'] == password:
            # 对比成功返回userid username
            return jsonify({"code":200,'mes':'登录成功','userid':mes['id'],'username':mes['username']})
        # 失败提示密码错误
        else:
            return jsonify({'code':10012,'mes':'密码错误'})
    else:
        return jsonify({'code':10011,'mes':'用户名不存在'})

@bp_course.route('/route_name')
def method_name():
    pass